<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\DiamondLog;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use think\Db;
use think\Exception;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->assign("currency", $this->model->getCurrencyList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['group', 'vip', 'club'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    public function tongguo($id = null)
    {
        $row = $this->model->get($id);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        Db::startTrans();
        try {
            $row->is_club = 1;
            $row->club_id = 2;
            $row->save();
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success();
    }

    public function jujue($id = null)
    {
        $row = $this->model->get($id);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        Db::startTrans();
        try {
            $row->is_club = 0;
            $row->save();
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success();
    }

    public function deduct($id = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $row = $this->model->get($params['id']);
            if (!$row) {
                $this->error(__('No Results were found'));
            }

            switch ($params['type']) {
                case "money":
                    $price_model = new MoneyLog();
                    break;
                case "score":
                    $price_model = new ScoreLog();
                    break;
                case "diamond":
                    $price_model = new DiamondLog();
                    break;
                case "gold":
                    $price_model = new GoldLog();
                    break;
                default:
                    $this->error("请选择类型");
            }
            Db::startTrans();
            try {
                $before = $row[$params['type']];
                $after = function_exists('bcadd') ? bcadd($row[$params['type']], $params['price'], 2) : $row[$params['type']] + $params['price'];
                $price_model->insert([
                    'user_id' => $row['id'], $params['type'] => $params['price'],
                    'before' => $before, 'after' => $after,
                    'memo' => $params['memo'], 'createtime' => time()
                ]);
                Db::name('user')->where('id', $row['id'])->update([$params['type'] => $after]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage(), "", $e->getTrace());
            }
            $this->success();
        }

        $this->assign("id", $id);
        return $this->fetch();
    }

    public function topup($id = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $row = $this->model->get($params['id']);
            if (!$row) {
                $this->error(__('No Results were found'));
            }

            switch ($params['type']) {
                case "money":
                    $price_model = new MoneyLog();
                    break;
                case "score":
                    $price_model = new ScoreLog();
                    break;
                case "diamond":
                    $price_model = new DiamondLog();
                    break;
                case "gold":
                    $price_model = new GoldLog();
                    break;
                default:
                    $this->error("请选择类型");
            }
            Db::startTrans();
            try {
                $before = $row[$params['type']];
                $after = function_exists('bcadd') ? bcadd($row[$params['type']], -$params['price'], 2) : $row[$params['type']] - $params['price'];
                $price_model->insert([
                    'user_id' => $row['id'], $params['type'] => -$params['price'],
                    'before' => $before, 'after' => $after,
                    'memo' => $params['memo'], 'createtime' => time()
                ]);
                Db::name('user')->where('id', $row['id'])->update([$params['type'] => $after]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage(), "", $e->getTrace());
            }
            $this->success();
        }

        $this->assign("id", $id);
        return $this->fetch();
    }

    public function banned($id = null)
    {
        $row = $this->model->get($id);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        Db::startTrans();
        try {
            $row->status = "hidden";
            $row->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

    public function normald($id = null)
    {
        $row = $this->model->get($id);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        Db::startTrans();
        try {
            $row->status = "normal";
            $row->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

    public function pass($id = null)
    {
        $row = $this->model->get($id);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        Db::startTrans();
        try {
            $row->real_status = 0;
            $row->real_name = "";
            $row->card_num = "";
            $row->save();
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success();
    }

    public function notpass($id = null)
    {
        $row = $this->model->get($id);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        Db::startTrans();
        try {
            $row->real_status = 1;
            $row->save();
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success();
    }
}
